package org.jeecg.modules.appuser.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.util.Date.DateUtil;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.modules.appuser.constant.PayTypeConstant;
import org.jeecg.modules.appuser.constant.TaskNamesConstant;
import org.jeecg.modules.appuser.entity.*;
import org.jeecg.modules.appuser.mapper.TbUserIntegralMapper;
import org.jeecg.modules.appuser.service.*;
import org.jeecg.modules.appuser.util.PayUtils;
import org.jeecg.modules.mall.entity.TbMnUser;
import org.jeecg.modules.mall.service.ITbMnUserService;
import org.jeecg.modules.system.service.ISysDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 用户积分表
 * @Author: jeecg-boot
 * @Date: 2020-05-19
 * @Version: V1.0
 */
@Service
@Slf4j
public class TbUserIntegralServiceImpl extends ServiceImpl<TbUserIntegralMapper, TbUserIntegral> implements ITbUserIntegralService {


    @Autowired
    private ITbUserIntegralDetailService tbUserIntegralDetailService;

    @Autowired
    @Lazy(true)
    private ITbUserGameBuidingService tbUserGameBuidingService;


    @Autowired
    private ISysDictService sysDictService;

    @Autowired
    @Lazy(true)
    private ITbUserIntegralConfigDetailService tbUserIntegralConfigDetailService;

    @Autowired
    private ITbIntegralExchangeConfigService tbIntegralExchangeConfigService;

    @Autowired
    private ITb_user_contributionService tb_user_contributionService;

    @Autowired
    private ITb_user_contribution_detailService tb_user_contribution_detailService;

    @Autowired
    @Lazy(true)
    private ITbMnUserService tbMnUserService;

    @Autowired
    private ITbUserNoticeService tbUserNoticeService;

    @Override
    public TbUserIntegral getOneByUserId(String user_id) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", user_id);
        return this.getOne(queryWrapper);
    }


    /**
     * 兑换用户积分
     * 1小时营业时间=20积分
     * 兑换的最小单位是一个小时，即只支持每20积分兑换一个小时
     * 最多可兑换24小时
     *
     * @param user_id
     * @param integral
     * @return
     */
    @Override
    public Result<?> integralExchangeBizHours(String user_id, BigDecimal integral) {

        TbUserIntegral tbUserIntegral = this.getOneByUserId(user_id);
        synchronized (tbUserIntegral) {
            BigDecimal integral_value = tbUserIntegral.getIntegral();
            int flag1 = integral.compareTo(new BigDecimal("20"));
            if (flag1 < 0) {
                return Result.error("积分不足,必须大于20");
            }
            int flag = integral.compareTo(integral_value);
            if (flag > 0) {
                return Result.error("积分不足");
            }
            BigDecimal new_integral = integral_value.subtract(integral);
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("user_id", user_id);
            TbUserGameBuiding tbUserGameBuiding = tbUserGameBuidingService.getOne(queryWrapper);
            int businessHours = tbUserGameBuiding.getBusinessHours();
            int addbizHours = integral.intValue() * 3;  //20积分等于1小时
//            if (addbizHours > 1440) {
//                return Result.error("明天再来兑换吧");
//            }
            int new_businessHours = businessHours + addbizHours;
            int totalConsumeHours = tbUserGameBuiding.getTotalConsumeHours() + addbizHours;
            tbUserGameBuiding.setBusinessHours(new_businessHours);
            tbUserGameBuiding.setTotalConsumeHours(totalConsumeHours);
            if (tbUserGameBuidingService.updateById(tbUserGameBuiding)) {
                //兑换营业时间  ，并记录明细
                saveIntegralDetail(tbUserIntegral, integral, new_integral);
            }
            return Result.ok("兑换成功");
        }
    }

    @Override
    public Result<?> showSignInDatabyWeek(String user_id) {
        Map<String, Object> resultMap = new HashMap<>();
        QueryWrapper queryWrapper = new QueryWrapper();
        log.info("第几周：" + DateUtil.getCurWeekNoOfYear());
        queryWrapper.eq("week_number", DateUtil.getCurWeekNoOfYear());
        queryWrapper.eq("user_id", user_id);
        queryWrapper.eq("task_name", TaskNamesConstant.Task_QIAN_DAO);
        List<TbUserIntegralConfigDetail> tbUserIntegralConfigDetailList = tbUserIntegralConfigDetailService.list(queryWrapper);
        List<DictModel> dictModelList = sysDictService.queryDictItemsByCode("signin_integral");
        resultMap.put("integralconfig", dictModelList);
        resultMap.put("tbUserIntegralConfigDetailList", tbUserIntegralConfigDetailList);

        return Result.ok(resultMap);
    }

    @Override
    public Map doActionTask(String user_id, String taskName) {

        Map<String, Object> resultMap = new HashMap<>();
        TbUserIntegralConfigDetail tbUserIntegralConfigDetail = tbUserIntegralConfigDetailService.getTodayTaskByName(taskName, user_id);
        Map<String, Object> resultData = verifyCompleteTask(tbUserIntegralConfigDetail);
        if (resultData != null) {

            return resultData;
        }
        BigDecimal rewardValue = tbUserIntegralConfigDetail.getRewardValue();
        TbUserIntegral tbUserIntegral = this.getOneByUserId(user_id);
        if (null != tbUserIntegral) {
            synchronized (tbUserIntegral) {
                if (tbUserIntegralConfigDetail.getTaskName().equals(TaskNamesConstant.Task_QIAN_DAO)) {
                    //查询这一周的签到情况
                    QueryWrapper queryWrapper = new QueryWrapper();
                    queryWrapper.eq("week_number", DateUtil.getCurWeekNoOfYear());
                    queryWrapper.eq("user_id", user_id);
                    queryWrapper.eq("signin_status", 1);
                    List<TbUserIntegralConfigDetail> tbUserIntegralConfigDetailList = tbUserIntegralConfigDetailService.list(queryWrapper);

                    if (null != tbUserIntegralConfigDetailList && tbUserIntegralConfigDetailList.size() > 0) {
                        int week_totalsignin_num = tbUserIntegralConfigDetailList.size();
                        int whichDayWeek = tbUserIntegralConfigDetail.getWhichDayWeek() - 1;
                        //如何相等，表示连续签到，则积分为连续签到积分
                        rewardValue = getAddIntegralBigDecimal(tbUserIntegralConfigDetail, week_totalsignin_num, whichDayWeek);
                    } else {
                        tbUserIntegralConfigDetail.setWhichDayWeek(DateUtil.getCurWeekNo());
                        tbUserIntegralConfigDetail.setWeekNumber(DateUtil.getCurWeekNoOfYear());
                    }
                }

                BigDecimal integral = tbUserIntegral.getIntegral();
                BigDecimal newIntegral = integral.add(rewardValue);
                tbUserIntegral.setIntegral(newIntegral);
                this.updateById(tbUserIntegral);
                //增加积分明细
                addIntegralDetail(tbUserIntegral, rewardValue, newIntegral, taskName);
                int actualFrequency = tbUserIntegralConfigDetail.getActualFrequency();
                //修改签到次数
                tbUserIntegralConfigDetail.setActualFrequency(actualFrequency + 1);
                //设置积分任务完成
                if (tbUserIntegralConfigDetail.getActualFrequency() == tbUserIntegralConfigDetail.getFrequency()) {
                    tbUserIntegralConfigDetail.setCompleteState(1);
                    tbUserIntegralConfigDetail.setSigninStatus(1);
                }

                //增加贡献值
                int contributionValue = tbUserIntegralConfigDetail.getContributionValue();
                int contributionFrequency = tbUserIntegralConfigDetail.getContributionFrequency();
                if (contributionFrequency > 0) {
                    QueryWrapper contributeQ = new QueryWrapper();
                    contributeQ.eq("user_id", user_id);
                    Tb_user_contribution tb_user_contribution = tb_user_contributionService.getOne(contributeQ);
                    Integer new_contributionValue = contributionValue + tb_user_contribution.getContributionValue();
                    tb_user_contribution.setContributionValue(new_contributionValue);
                    if (saveUserContributionValueDetail(tb_user_contribution, contributionValue, new_contributionValue, taskName)) {
                        tb_user_contributionService.updateById(tb_user_contribution);
                    }
                    tbUserIntegralConfigDetail.setContributionFrequency(contributionFrequency - 1);
                }

                tbUserIntegralConfigDetailService.updateById(tbUserIntegralConfigDetail);
                resultMap.put("state", 1);
                resultMap.put("msg", "任务完成");
            }
        }
        return resultMap;
    }

    private boolean saveUserContributionValueDetail(Tb_user_contribution tb_user_contribution, int contributionValue, Integer new_contributionValue, String taskName) {
        Tb_user_contribution_detail tb_user_contribution_detail = new Tb_user_contribution_detail();
        tb_user_contribution_detail.setAfterContributionValue(new_contributionValue);
        tb_user_contribution_detail.setContributionValue(contributionValue);
        tb_user_contribution_detail.setType(PayTypeConstant.PAYTYPE_INCOME);
        tb_user_contribution_detail.setUserId(tb_user_contribution.getUserId());
        tb_user_contribution_detail.setValueFrom(taskName);
        tb_user_contribution_detailService.save(tb_user_contribution_detail);
        return true;
    }

    @Override
    public Result<?> buyIntegral(String user_id, String integral_exchange_id, Double price, int num, String return_url) {

        TbIntegralExchangeConfig tbIntegralExchangeConfig = tbIntegralExchangeConfigService.getById(integral_exchange_id);
        String trade_order_id = UUIDGenerator.generate();
        String url = PayUtils.pay(tbIntegralExchangeConfig.getId(), price, num, return_url, trade_order_id);
        if (!StringUtils.isEmpty(url)) {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("user_id", user_id);
            TbUserIntegral tbUserIntegral = this.getOne(queryWrapper);
            BigDecimal bigDecimal = tbUserIntegral.getIntegral();
            BigDecimal integral = new BigDecimal(tbIntegralExchangeConfig.getIntegral());
            BigDecimal new_integral = bigDecimal.add(integral);
            addIntegralDetailByOrder(tbUserIntegral, integral, new_integral, TaskNamesConstant.Task_INTEGRAL_EXCHANGE, trade_order_id, tbIntegralExchangeConfig.getId(), PayTypeConstant.PAYTYPE_INCOME);
            //  tbUserIntegral.setIntegral(new_integral);
            //  tbUserIntegralService.updateById(tbUserIntegral);
            return Result.ok(url);
        }
        return Result.error("接口调用失败");
    }

    @Override
    public Result<?> returnPay(String trade_order_id, BigDecimal total_fee, String trade_order_id1, String status, String appid) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("remark", trade_order_id);
        TbUserIntegralDetail tbUserIntegralDetail = tbUserIntegralDetailService.getOne(queryWrapper);
        if (null != tbUserIntegralDetail) {
            TbIntegralExchangeConfig tbIntegralExchangeConfig = tbIntegralExchangeConfigService.getById(tbUserIntegralDetail.getIntegralExchangeId());
            String userId = tbUserIntegralDetail.getUserId();
            QueryWrapper new_queryWrapper = new QueryWrapper();
            new_queryWrapper.eq("user_id", userId);
            TbUserIntegral tbUserIntegral = this.getOne(new_queryWrapper);
            BigDecimal bigDecimal = tbUserIntegral.getIntegral();
            BigDecimal integral = new BigDecimal(tbIntegralExchangeConfig.getIntegral());
            BigDecimal new_integral = bigDecimal.add(integral);
            tbUserIntegral.setIntegral(new_integral);
            this.updateById(tbUserIntegral);
            tbUserIntegralDetail.setState(1);
            tbUserIntegralDetailService.updateById(tbUserIntegralDetail);
            return Result.ok("测试ok");
        }

        return Result.error("测试失败");
    }

    @Override
    public Result<?> integralUpgradeAgent(String user_id) {

        TbUserIntegral tbUserIntegral = this.getOneByUserId(user_id);
        BigDecimal integral = tbUserIntegral.getIntegral();
        BigDecimal upgrade_integral = new BigDecimal(10000);
        if (integral.compareTo(upgrade_integral) < 0) {
            return Result.error("积分不足!");
        }
        List<DictModel> dictModelList = sysDictService.queryDictItemsByCode("agent_person_num");
        int agent_person_num = Integer.valueOf(dictModelList.get(0).getValue());

        BigDecimal new_integral = integral.subtract(upgrade_integral);
        tbUserIntegral.setIntegral(new_integral);
        if (this.updateById(tbUserIntegral)) {
            addIntegralDetailByOrder(tbUserIntegral, integral, new_integral, TaskNamesConstant.Task_INTEGRAL_UPGRADE_AGENT, "", "", PayTypeConstant.PAYTYPE_EXPEND);
            TbMnUser tbMnUser = tbMnUserService.getById(user_id);
            //设置成为代理
            tbMnUser.setIntegralAgent(1);
            if (tbMnUserService.updateById(tbMnUser)) {
                log.info("代理升级成功");
            }
            //查询邀请人，查询是否10个代理人，升级高级代理
            upgradeAgent1(tbMnUser, agent_person_num, true);

        }
        return Result.ok("升级完成");

    }


    /**
     * @param tbMnUser
     * @return
     */
    private boolean upgradeAgent1(TbMnUser tbMnUser, Integer agent_person_num, boolean next_agent_status) {

        //查询被邀请人  是否  够升级数量,如果狗，升级邀请人
        QueryWrapper queryWrapper2 = new QueryWrapper();
        queryWrapper2.eq("invite_code", tbMnUser.getRegisterCode());
        TbMnUser tbMnUser2 = tbMnUserService.getOne(queryWrapper2);
        if (null != tbMnUser2) {
            Tb_user_contribution tb_user_contribution = tb_user_contributionService.getOneByUserId(tbMnUser2.getId());
            Integer agent_num = tbMnUser2.getIntegralAgent();
            QueryWrapper queryWrapper1 = new QueryWrapper();
            queryWrapper1.eq("register_code", tbMnUser.getRegisterCode());
            queryWrapper1.ge("integral_agent", agent_num);
            List<TbMnUser> tbMnUserList = tbMnUserService.list(queryWrapper1);
            if (null != tbMnUserList && tbMnUserList.size() >= agent_person_num) {
                agent_num += 1;
            }
            if (agent_num > 3) {
                agent_num = 3;
            }

            //得到 升级后的贡献度
            String add_contribution_name = "";//getReturnContributionNameByText(agent_num);
            if(agent_num==1){
                add_contribution_name="代理";
            }
            if(agent_num==2){
                add_contribution_name="高级代理";
            }
            if(agent_num==3){
                add_contribution_name="城市合伙人";
            }
            if(!next_agent_status){
                add_contribution_name="间接"+add_contribution_name;
            }
            String add_contribution = getReturnContributionValue(add_contribution_name);
            Integer contribution_value = tb_user_contribution.getContributionValue();
            Integer new_contribution = contribution_value + Integer.valueOf(add_contribution);
            tb_user_contribution.setContributionValue(new_contribution);
            if (saveUserContributionValueDetail(tb_user_contribution, contribution_value, new_contribution, add_contribution_name)) {
                //增加贡献图
                tb_user_contributionService.updateById(tb_user_contribution);
            }
            //增加邀请人 的通知
            tbMnUser2.setIntegralAgent(agent_num);
            tbMnUserService.updateById(tbMnUser2);
            //加入通知
            TbUserNotice tbUserNotice = new TbUserNotice();
            tbUserNotice.setNoticeContent(tbMnUser.getPhone() + ":" + add_contribution_name + "代理升级成功");
            tbUserNotice.setNoticeTitle(cn.hutool.core.date.DateUtil.now() + ":升级完成");
            tbUserNotice.setNoticeSendStatus("0");
            tbUserNotice.setUserId(tbMnUser.getId());
            tbUserNotice.setNoticeType("1");
            tbUserNoticeService.addUserNotice(tbUserNotice);
            if(next_agent_status){
                upgradeAgent1(tbMnUser2, agent_person_num, false);
            }


        }
        return true;
    }

    private String getReturnContributionValue(String agent_name) {
        List<DictModel> dictModelList = sysDictService.queryDictItemsByCode("agent_contribution_value");
        String add_contribution = "0";
        for (DictModel dictModel : dictModelList) {
            if (dictModel.getText().trim().equals(String.valueOf(agent_name))) {
                add_contribution = dictModel.getValue();
            }
        }
        return add_contribution;
    }

    private String getReturnContributionValueByText(Integer agent_num) {
        List<DictModel> dictModelList = sysDictService.queryDictItemsByCode("agent_contribution_value");
        String add_contribution = "0";
        for (DictModel dictModel : dictModelList) {
            if (dictModel.getValue().trim().equals(String.valueOf(agent_num))) {
                add_contribution = dictModel.getValue();
            }
        }
        return add_contribution;
    }

    private String getReturnContributionNameByText(Integer agent_num) {
        List<DictModel> dictModelList = sysDictService.queryDictItemsByCode("agent_contribution_value");
        String add_contribution = "代理";
        for (DictModel dictModel : dictModelList) {
            if (dictModel.getValue().trim().equals(String.valueOf(agent_num))) {
                add_contribution = dictModel.getText();
            }
        }
        return add_contribution;
    }

    private Map<String, Object> verifyCompleteTask(TbUserIntegralConfigDetail tbUserIntegralConfigDetail) {
        Map<String, Object> resultMap = new HashMap<>();
        if (null == tbUserIntegralConfigDetail) {
            resultMap.put("state", 0);
            resultMap.put("msg", "无此任务");
            return resultMap;
        }
        if (tbUserIntegralConfigDetail.getActualFrequency() == tbUserIntegralConfigDetail.getFrequency()) {
            resultMap.put("state", 0);
            resultMap.put("msg", "任务已经完成，期待明天吧");
            return resultMap;
        }

        if (tbUserIntegralConfigDetail.getCompleteState() == 1) {
            resultMap.put("state", 0);
            resultMap.put("msg", "任务已经完成，期待明天吧");
            return resultMap;
        }
        return null;
    }

    private void addIntegralDetailByOrder(TbUserIntegral tbUserIntegral, BigDecimal integral, BigDecimal newIntegral, String task_QIAN_DAO, String order_id, String integral_exchange_id, String inOrOut) {
        TbUserIntegralDetail tbUserIntegralDetail = new TbUserIntegralDetail();
        tbUserIntegralDetail.setUserId(tbUserIntegral.getUserId());
        tbUserIntegralDetail.setBalanceAfter(newIntegral);
        tbUserIntegralDetail.setBalance(integral);
        tbUserIntegralDetail.setState(0);
        tbUserIntegralDetail.setIntegralId(tbUserIntegral.getId());
        tbUserIntegralDetail.setFromType(task_QIAN_DAO);
        //tbUserIntegralDetail.setInOrOut(PayTypeConstant.PAYTYPE_INCOME);
        tbUserIntegralDetail.setInOrOut(inOrOut);
        tbUserIntegralDetail.setRemark(order_id);
        tbUserIntegralDetail.setIntegralExchangeId(integral_exchange_id);
        tbUserIntegralDetailService.save(tbUserIntegralDetail);
    }

    private void addIntegralDetail(TbUserIntegral tbUserIntegral, BigDecimal integral, BigDecimal newIntegral, String task_QIAN_DAO) {
        TbUserIntegralDetail tbUserIntegralDetail = new TbUserIntegralDetail();
        tbUserIntegralDetail.setUserId(tbUserIntegral.getUserId());
        tbUserIntegralDetail.setBalanceAfter(newIntegral);
        tbUserIntegralDetail.setBalance(integral);
        tbUserIntegralDetail.setState(1);
        tbUserIntegralDetail.setIntegralId(tbUserIntegral.getId());
        tbUserIntegralDetail.setFromType(task_QIAN_DAO);
        tbUserIntegralDetail.setInOrOut(PayTypeConstant.PAYTYPE_INCOME);
        tbUserIntegralDetailService.save(tbUserIntegralDetail);
    }


    private BigDecimal getAddIntegralBigDecimal(TbUserIntegralConfigDetail tbUserIntegralConfigDetail, int week_totalsignin_num, int whichDayWeek) {
        BigDecimal addIntegralBigDecimal = new BigDecimal(0);
        List<DictModel> dictModelList = sysDictService.queryDictItemsByCode("signin_integral");
        if (week_totalsignin_num == whichDayWeek) {
            for (DictModel dictModel : dictModelList) {
                int whichDayWeek1 = tbUserIntegralConfigDetail.getWhichDayWeek();
                if (dictModel.getText().trim().equals(String.valueOf(whichDayWeek1))) {
                    String addIntegral = dictModel.getValue();
                    addIntegralBigDecimal.add(new BigDecimal(addIntegral));
                }
            }
        } else {
            String num_str = dictModelList.get(0).getValue();
            addIntegralBigDecimal.add(new BigDecimal(num_str));
        }
        return addIntegralBigDecimal;
    }

    private boolean saveIntegralDetail(TbUserIntegral tbUserIntegral, BigDecimal joinIntegral, BigDecimal newbigdecimal) {
        TbUserIntegralDetail tbUserIntegralDetail = new TbUserIntegralDetail();
        tbUserIntegralDetail.setBalance(joinIntegral);
        tbUserIntegralDetail.setFromType(PayTypeConstant.PAYFORM_EXCHANGE_BIZ_HOURS);
        tbUserIntegralDetail.setInOrOut(PayTypeConstant.PAYTYPE_EXPEND);
        tbUserIntegralDetail.setIntegralId(tbUserIntegral.getId());
        tbUserIntegralDetail.setBalanceAfter(newbigdecimal);
        tbUserIntegralDetail.setUserId(tbUserIntegral.getUserId());
        tbUserIntegralDetail.setState(1);
        if (tbUserIntegralDetailService.save(tbUserIntegralDetail)) {
            tbUserIntegral.setIntegral(newbigdecimal);
            this.updateById(tbUserIntegral);
            return true;
        }
        return false;
    }
}
